package com.xxc.hs.funActivity.waring;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.tplink.sdk.tpopensdk.TPPlayer;
import com.tplink.sdk.tpopensdk.common.TPSDKCommon;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class ScreenshotManager {
    private static final String TAG = "ScreenshotManager";
    private static final int STORAGE_PERMISSION_REQUEST_CODE = 1001;
    private static final String DIRECTORY_NAME = "SmartFarmScreenshots";

    private File customDir;
    private Context context;
    private Activity activity;

    public ScreenshotManager(Context context, Activity activity) {
        this.context = context;
        this.activity = activity;
        customDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                DIRECTORY_NAME
        );
    }

    /**
     * 检查并申请存储权限
     */
    public boolean checkAndRequestPermission() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(context, "需要存储权限来保存截图", Toast.LENGTH_SHORT).show();
            }
            ActivityCompat.requestPermissions(
                    activity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    STORAGE_PERMISSION_REQUEST_CODE
            );
            return false;
        }
        return true;
    }

    /**
     * 保存截图（生成标准格式文件名）
     */
    public String saveScreenshot(TPPlayer m_TPPlayer) {
        if (!checkAndRequestPermission()) {
            return "权限未授权";
        }

        if (m_TPPlayer == null) {
            return "m_TPPlayer is null";
        }

        if (!customDir.exists()) {
            boolean created = customDir.mkdirs();
            if (!created) {
                Log.e(TAG, "文件夹创建失败");
                return "文件夹创建失败";
            }
        }

        try {
            // 生成新格式时间戳：yyyyMMdd_HHmmss（便于文件名存储和解析）
            String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
            String fileName = "waring_" + timestamp + ".jpg";
            File saveFile = new File(customDir, fileName);
            String savePath = saveFile.getAbsolutePath();

            int screenshotSuccess = m_TPPlayer.snapshot(savePath);

            if (TPSDKCommon.ErrorCode.IPC_EC_OK == screenshotSuccess) {
                Log.d(TAG, "截图保存成功: " + savePath);
                updateMediaLibrary(saveFile);
                return "保存成功";
            } else {
                Log.e(TAG, "截图操作失败，错误码: " + screenshotSuccess);
                return "截图操作失败";
            }
        } catch (Exception e) {
            Log.e(TAG, "保存截图异常", e);
            return "保存异常: " + e.getMessage();
        }
    }

    /**
     * 通知系统更新媒体库
     */
    private void updateMediaLibrary(File file) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
        Log.d(TAG, "媒体库已更新: " + file.getAbsolutePath());
    }

    /**
     * 处理权限申请结果
     */
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "存储权限已授权");
            } else {
                Log.e(TAG, "存储权限被拒绝，无法保存截图");
            }
        }
    }

    /**
     * 获取截图保存目录（供展示页面使用）
     */
    public File getScreenshotsDirectory() {
        return customDir;
    }
}